<template>
  <div class="content">
    <e-heading grade='1'>教练信息</e-heading>
    <el-form ref="form" v-bind="getFormProps()">
      <el-form-item label="姓名：" prop="name" :rules="[
          { required: true, message: '请输入教练姓名'},
          { min: 2, message: '请输入全名'},
          Object.assign({trigger: 'blur'}, validator.rule.userName)
        ]">
        <el-row>
          <el-col :span="16">
            <el-input :maxlength="40" v-model.trim="form.name" placeholder="请输入教练姓名" v-focus></el-input>
          </el-col>
        </el-row>
      </el-form-item>
      <el-form-item label="性别：" prop="sex" :rules="[
              { required: true, message: '请选择性别'},
            ]">
        <el-radio-group v-model="form.sex">
          <el-radio :label="1">男</el-radio>
          <el-radio :label="2">女</el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item label="国籍：" prop="nationality" :rules="[
              { required: true, message: '请选择国籍'},
            ]">
        <el-row>
          <el-col :span="16">
          <el-select v-model="form.nationality" placeholder="请选择国籍" style="width: 100%;" filterable>
            <el-option v-for="item in country_list" :key="item.id" :value="item.countryCode" :label="item.countryChineseName">
            </el-option>
          </el-select>
        </el-col>
      </el-row> 
      </el-form-item>
      <el-form-item label="所在省市：" prop="provinceId">
        <el-row>
          <el-col :span="16">
            <el-select v-model="address" clearable placeholder="请选择省市" style="width: 100%;" >
              <el-option
                v-if='train_compus_selection'
                v-for="(item, index) in provinceAreaOptions"
                :key="index"
                :label="item.text"
                :value="item.id">
              </el-option>
            </el-select>
          </el-col>
        </el-row> 
      </el-form-item>
      <el-form-item label="证件号码：" prop="idNo" :rules="[
          { required: true, message: '请输入有效证件号码'},
          Object.assign({trigger: 'blur', validator: validator.rule.isIp.validator.bind(this)})
        ]">
        <el-row>
          <el-col :span="16">
            <e-identity :select-value.sync="form.idType" v-model="form.idNo" @blur="handleIp(form.idNo)" />
          </el-col>
        </el-row>
      </el-form-item>
      <el-form-item label="出生日期：" prop="birthday" :rules="[
              { required: false, message: '请选择出生日期'},
            ]">
        <el-row>
          <el-col :span="16">
            <el-date-picker
              :editable="true"
              v-model="form.birthday"
              type="date"
              placeholder="选择日期"
              :picker-options="pickerOptions"
              style="width: 100%">
            </el-date-picker>
          </el-col>
        </el-row>
      </el-form-item>
      <el-form-item label="联系手机：" prop="mobile" :rules="[
          { required: true, message: '请输入手机号'},
          Object.assign({trigger: 'blur'}, validator.rule.mobile)
        ]">
        <el-row>
          <el-col :span="16">
            <el-input v-model="form.mobile" :maxlength="11" :disabled="this.$route.path.indexOf('add') == -1" placeholder="请输入手机号" />
            <p class="small phone-tips">若要修改手机号，请该教练在"求苗"APP操作"我的"-"设置"-"账号安全"-"账号绑定"-"手机号"进行修改</p>
          </el-col>
        </el-row>
      </el-form-item>
      <el-form-item label="教练照片： " prop="photo" :rules="[ 
          { required: true, message: '请上传教练照片！'}, 
        ]">
        <e-img-upload v-model="form.photo" :is-crop="true"/>
      </el-form-item>
      <el-form-item label="执教年限：" prop="teachYear" :rules="[
          Object.assign({trigger: 'blur', validator: checkYear})
        ]">
        <el-input-number :bit="0.1" :min="0" :max="99" v-model="form.teachYear" placeholder="请填写学员的臂展">
          <template slot="append">年</template>
        </el-input-number>
      </el-form-item>
      <el-form-item label="机构认证：">
        <el-row>
          <el-col :span="16">
            <el-input v-model="form.orgAuthority" :maxlength="60" number-word />
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <span class="form-help warn-tips">机构认证为培训机构内部认证的等级和标准</span>
          </el-col>
        </el-row>
      </el-form-item>
      <el-form-item label="证书：" prop="certificateImages" :rules="[
              { required: false, message: '请上传证书'},
            ]">
        <e-img-group-upload :size="1024*1024*3" v-model="form.certificateImages" :limit="4"/>
      </el-form-item>
      <el-form-item label="证书名称：" prop="certificateName">
        <el-col :span="24">
          <el-input :maxlength="200" v-model.trim="form.certificateName" placeholder="请输入证书名称，以顿号隔开"></el-input>
        </el-col> 
      </el-form-item>
      <el-form-item label="教练简介：" prop="intro">
        <el-col :span="24">
          <el-input v-model="form.intro" :maxlength="1000" type="textarea" :rows="4" number-word />
        </el-col>
      </el-form-item>
      <el-form-item label="备注：" prop="remark">
        <el-col :span="24">
          <el-input :maxlength="200" v-model.trim="form.remark"></el-input>
        </el-col> 
      </el-form-item>
      <div class="button-box">
        <router-link to="/training/coach">
          <el-button>取消</el-button>
        </router-link>
        <el-button type="primary" native-type="submit" :loading="loading">保存</el-button>
      </div>
    </el-form>
  </div>
</template>

<script>
import { form } from 'utils/mixins'
import validator from 'utils/validator'
import EImgUpload from '@e-ui/ImgUpload'
import EImgGroupUpload from '@e-ui/ImgGroupUpload'
import { mapGetters } from 'vuex'
import api from 'api/train'
import EIdentity from '@e-ui/Identity'
export default {
  mixins: [form],
  components: {
    EImgUpload,
    EImgGroupUpload,
    EIdentity
  },
  computed: {
    ...mapGetters({
      train_coach_info: 'train_coach_info', // 教练信息
      country_list: 'country_list',
      train_compus_selection: 'train_compus_selection'
    }),
    provinceAreaOptions () {
      if (this.train_compus_selection && this.train_compus_selection.length > 0) {
        let arr = this.train_compus_selection
        let result = []
        for (let item of arr) {
          let mid = {
            id: `${item.provinceId}${item.cityId}`,
            value: [item.provinceId, item.cityId],
            text: `${item.provinceName}-${item.cityName}`
          }
          result.push(mid)
        }
        return result
      }
    },
    address: {
      get () {
        if (this.form.provinceId) {
          return `${this.form.provinceId}${this.form.cityId}`
        } else {
          this.form.provinceId = ''
          this.form.cityId = ''
          return ''
        }
      },
      set (newVal) {
        if (newVal) {
          for (let item of this.provinceAreaOptions) {
            let itemId = item.id
            if (itemId === newVal) {
              this.form.provinceId = item.value[0]
              this.form.cityId = item.value[1]
            }
          }
        } else {
          this.form.provinceId = ''
          this.form.cityId = ''
        }
      }
    }
  },
  data () {
    return {
      checkYear: (rule, value, callback) => {
        if (value) {
          if (Number.isInteger(value)) {
            callback()
          } else {
            callback(new Error('请输入正整数!'))
          }
        } else {
          callback()
        }
      },
      validator,
      loading: false,
      isChecked: false,
      form: {
        name: '',
        sex: 1,
        nationality: '',
        idType: 1,
        idNo: '', // 证件号码
        birthday: '',
        mobile: '',
        photo: '',
        certificateImages: [], // 证书
        certificateName: '', // 证书名称
        intro: '',
        remark: '',
        provinceId: '',
        cityId: '',
        orgAuthority: '', // 机构认证
        teachYear: '' // 执教年限
      },
      pickerOptions: {
        disabledDate (time) { // 只能选择过去时间
          return time.getTime() > Date.now()
        }
      },
      dialogCoupon: false
    }
  },
  created () {
    if (this.$route.path === '/training/coach/edit') {
      this.$store.dispatch('train_coach_info', {teacherId: this.$route.query.id})
    }
    this.$store.dispatch('country_list')
    this.$store.dispatch('train_compus_selection')
  },
  watch: {
    train_coach_info (value) {
      this.form.name = value.name
      this.form.sex = value.sex
      this.form.nationality = value.nationality
      this.form.idType = value.idType
      this.form.idNo = value.idNo
      this.form.birthday = new Date(value.birthday).getTime()
      this.form.mobile = value.mobile
      this.form.certificateName = value.certificateName
      this.form.intro = value.intro
      this.form.remark = value.remark
      this.form.photo = value.photo
      this.form.certificateImages = value.certificateImages
      this.form.provinceId = value.provinceId
      this.form.cityId = value.cityId
      this.form.teachYear = value.teachYear
      this.form.orgAuthority = value.orgAuthority
    }
  },
  methods: {
    handleIp (value) { // 根据身份证自动输入生日日期
      if (this.form.idType) {
        this.form.birthday = new Date(`${value.substring(6, 10)}-${value.substring(10, 12)}-${value.substring(12, 14)}`).getTime() // es6语法
      }
    },
    handleSuccess (url) {
      this.form.photo = url
      this.dialogCoupon = false
    },
    uploadCropper (res) {
      this.$refs.cropper.uploadCropper()
    },
    cancleCropper () {
      this.dialogCoupon = false
      this.$refs.cropper.resetCropper()
    },
    submit () {
      let data = Object.assign({id: this.$route.query.id}, this.form)
      delete data.birthday
      if (this.$route.path === '/training/coach/edit') {
        let newData = Object.assign({birthday: this.form.birthday ? new Date(this.form.birthday).getTime() : ''}, data)
        api.editCoach(newData, {context: this, successMsg: '修改成功'}).then(res => {
          history.back()
        })
      } else {
        delete data.id
        let newData = Object.assign({birthday: this.form.birthday ? new Date(this.form.birthday).getTime() : ''}, data)
        api.editCoach(newData, {context: this, successMsg: '新增成功'}).then(res => {
          history.back()
        })
      }
    }
  }
}
</script>

<style lang="scss" scoped>
.content {
  .el-radio-group .el-radio {
    min-width: 40px;
  }
  .warn-tips {
    margin-left: 0px;
  }
}
.phone-tips{
  width: 150%;
  color:#909090;
}
</style>
